import { Navigate, Outlet } from 'react-router-dom';
import Login from '../views/login.tsx';
import Home from '../views/home.tsx';
import Index from '../views/index.tsx';
import Category from '../views/category.tsx'; // 新增分类页
import Cart from '../views/cart.tsx'; // 新增购物车页
import Mine from '../views/mine.tsx'; // 新增个人页
import Quanbu from '../views/quanbu.tsx';
import xiangqing from '../views/xiangqing.tsx';
import Xiangqing from '../views/xiangqing.tsx';

const PrivateRoute = () => {
    const token = localStorage.getItem('token');
    const isLogin = !!token;

    if (!isLogin) {
        const currentPath = window.location.pathname;
        const publicPaths = ['/login', '/register', '/forgot-password', '/sms-login', '/user-agreement'];

        if (!publicPaths.includes(currentPath)) {
            sessionStorage.setItem('redirectPath', currentPath);
        }

        return <Navigate to="/login" replace />;
    }

    return <Outlet />;
};

const routes = [
    {
        path: '/login',
        element: <Login />
    },
    {
        path: '/',
        element: <PrivateRoute />,
        children: [
            {
                path: '/',
                element: <Index />
            },
            {
                path: 'home',
                element: <Home />
            },
            {
                path: 'category',
                element: <Category /> // 分类页路由
            },
            {
                path: 'cart',
                element: <Cart /> // 购物车页路由
            },
            {
                path: 'mine',
                element: <Mine /> // 个人页路由
            },
            {
                path: 'quanbu',
                element: <Quanbu /> // 全部订单
            },
            {
                path: 'xiangqing/:id',
                element: <Xiangqing /> // 详情页
            }
        ]
    },
    {
        path: '*',
        element: <Navigate to="/" replace />
    }
];

export default routes;